package com.dream.controller;

import com.alibaba.fastjson.JSON;
import com.dream.pojo.User;
import com.dream.service.UserService;
import com.dream.service.impl.UserServiceImpl;
import com.dream.utils.PageUtil;
import com.dream.utils.ResultCommon;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@WebServlet("/UserController.do")
public class UserController extends BaseServlet {

    UserService us = new UserServiceImpl();

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String isRememberPwd = request.getParameter("isRememberPwd"); //是否保存密码
        String role = request.getParameter("role");
        User user = new User(username, password, role);
        User loginUser = us.login(user);
        if (loginUser != null) {
            //登录成功
            if ("1".equals(isRememberPwd)) {
                //记住账号和密码
                Cookie cookie = new Cookie("userToken", URLEncoder.encode(loginUser.getUserName() + " " + loginUser.getPassword(), "UTF-8"));
                Cookie role_cookie = new Cookie("role_cookie", URLEncoder.encode(loginUser.getRole(), "UTF-8"));
                cookie.setMaxAge(60 * 60 * 24);
                role_cookie.setMaxAge(60 * 60 * 24);
                cookie.setPath("/");
                role_cookie.setPath("/");
                response.addCookie(cookie);
                response.addCookie(role_cookie);
            } else {
                Cookie cookie = new Cookie("userToken", "");
                Cookie role_cookie = new Cookie("role_cookie", URLEncoder.encode("", "UTF-8"));
                cookie.setMaxAge(0);
                role_cookie.setMaxAge(0);
                cookie.setPath("/");
                role_cookie.setPath("/");
                response.addCookie(cookie);
                response.addCookie(role_cookie);
            }
            //存储用户的session信息
            HttpSession session = request.getSession();
            session.setAttribute("loginUser", loginUser);
            //登录成功后台首页
            response.sendRedirect("main.jsp");
        } else {
            request.setAttribute("msg", "账号或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        //注销调整登录页面
        response.sendRedirect("login.jsp");
    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultCommon resultCommon = null;
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String realName = request.getParameter("realName");
        String phone = request.getParameter("phone");
        String role = request.getParameter("role");
        String remark = request.getParameter("remark");
        User user = new User(userName, password, realName, phone, role, remark, System.currentTimeMillis(), System.currentTimeMillis());
        int count = us.add(user);
        if (count > 0) {
            resultCommon = new ResultCommon(200, "新增成功", null);
        } else {
            resultCommon = new ResultCommon(500, "新增异常", null);
        }
        String toJSONString = JSON.toJSONString(resultCommon);
        response.getWriter().write(toJSONString);
    }

    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName"); //条件1
        String pageIndex = request.getParameter("pageIndex"); //条件4  当前页码
        if (pageIndex == null || "".equals(pageIndex)) {
            pageIndex = "1";//默认值
        }
        String pageSize = request.getParameter("pageSize"); //条件5   页面大小
        if (pageSize == null || "".equals(pageSize)) {
            pageSize = "5";//默认值
        }
        //条数
        long totalCount = us.totalCount(userName);
        //每页数据
        List<User> departmentList = us.list(userName, Long.valueOf(pageIndex), Long.valueOf(pageSize));
        for (User user : departmentList) {
            String role = user.getRole();
            if("1".equals(role)){
                user.setRoleName("超级管理员");
            }else if("2".equals(role)){
                user.setRoleName("宿舍管理员");
            }else{
                user.setRoleName("学生");
            }
        }

        //封装一个分页的工具类
        PageUtil<User> pageUtil = new PageUtil<User>(Long.valueOf(pageIndex), Long.valueOf(pageSize), totalCount, departmentList);
        //存值转发
        request.setAttribute("pageUtil", pageUtil);
        request.setAttribute("userName", userName); //回显
        request.getRequestDispatcher("viewUserInfo.jsp").forward(request, response);
    }

    public void goupdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id=request.getParameter("id");
        User user = us.findById(id);
        request.setAttribute("user",user);
        request.getRequestDispatcher("updateUser.jsp").forward(request,response);
    }

    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultCommon resultCommon = null;
        String id = request.getParameter("id");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String realName = request.getParameter("realName");
        String phone = request.getParameter("phone");
        String role = request.getParameter("role");
        String remark = request.getParameter("remark");
        User user = new User(Long.valueOf(id),userName, password, realName, phone, role, remark, System.currentTimeMillis());
        int count = us.update(user);
        if (count > 0) {
            resultCommon = new ResultCommon(200, "更新成功", null);
        } else {
            resultCommon = new ResultCommon(500, "更新异常", null);
        }
        String toJSONString = JSON.toJSONString(resultCommon);
        response.getWriter().write(toJSONString);
    }

    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        int count = us.deleteById(id);
        if (count > 0) {
            response.getWriter().write("<script>alert('删除成功');location.href='/UserController.do?action=list';</script>");
        } else {
            response.getWriter().write("<script>alert('删除异常');location.href='/UserController.do?action=list';</script>");
        }
    }

    /**
     * 更新个人信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultCommon resultCommon = null;
        String id = request.getParameter("id");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String realName = request.getParameter("realName");
        String phone = request.getParameter("phone");
        String role = request.getParameter("role");
        String remark = request.getParameter("remark");
        User user = new User(Long.valueOf(id),userName, password, realName, phone, role, remark, System.currentTimeMillis());
        int count = us.update(user);
        if (count > 0) {
            resultCommon = new ResultCommon(200, "更新成功", null);
            //清除session
            request.getSession().invalidate();
            //清除cookie
            Cookie cookie = new Cookie("userToken", "");
            Cookie role_cookie = new Cookie("role_cookie", URLEncoder.encode("", "UTF-8"));
            cookie.setMaxAge(0);
            role_cookie.setMaxAge(0);
            cookie.setPath("/");
            role_cookie.setPath("/");
            response.addCookie(cookie);
            response.addCookie(role_cookie);
        } else {
            resultCommon = new ResultCommon(500, "更新异常", null);
        }
        String toJSONString = JSON.toJSONString(resultCommon);
        response.getWriter().write(toJSONString);
    }

}
